package com.ai.chat.service;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Stream;
import com.ai.chat.adapter.MultipleAgentFullChatAdapter;
import com.ai.chat.domain.base.BaseAgent;
import com.ai.chat.domain.base.BaseAgentConfig;
import com.ai.chat.domain.base.BaseFile;
import com.ai.chat.domain.base.BaseHistory;
import com.ai.chat.domain.base.BaseTag;
import com.ai.chat.domain.base.request.BaseChatRequest;
import com.ai.chat.domain.base.request.BaseQuery;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;

@Service
public class OllamaService extends MultipleAgentFullChatAdapter {
    private final List<BaseHistory> historyList = new CopyOnWriteArrayList<>();

    @Resource
    private OllamaChatModel ollamaChatModel;

    private final ConcurrentHashMap<String, Disposable> streamDisposableMap = new ConcurrentHashMap<>();

    private final ConcurrentHashMap<String, MultipartFile> fileMap = new ConcurrentHashMap<>();

    @Override
    public Flux<String> streamChat(BaseChatRequest request, HttpServletResponse response) {
        String streamId = UUID.randomUUID().toString().replaceAll("-", "");
        response.setHeader("X-Stream-Id", streamId);
        return ollamaChatModel.stream(request.getMessage())
                .doOnSubscribe(sub -> {
                    // 将Subscription转换为Disposable
                    Disposable disposable = sub::cancel;
                    streamDisposableMap.put(streamId, disposable);
                })
                .doOnCancel(() -> disposeStream(streamId))
                .doFinally(signal -> streamDisposableMap.remove(streamId));
    }

    @Override
    public void disposeStream(String streamId) {
        Disposable disposable = streamDisposableMap.get(streamId);
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            streamDisposableMap.remove(streamId);
        }
    }

    @Override
    public String chat(BaseChatRequest request) {
        return ollamaChatModel.call(request.getMessage());
    }

    @Override
    public List<BaseAgent> getAgentList(BaseQuery query) {
        // 配置
        BaseAgentConfig config1 = new BaseAgentConfig();
        config1.setName("deepseek");
        config1.setPrompt("我是你的AI智能助理，你可以问我任何问题！");
        config1.setStreamFlag(true);
        config1.setNetQueryFlag(true);
        config1.setAttachFlag(true);
        config1.setDeepThinkFlag(true);
        config1.setMultipleAgentFlag(true);
        config1.setHistoryFlag(true);

        BaseAgentConfig config2 = config1.clone();
        config2.setName("deepseek-r2");
        config2.setPrompt("我是你的AI智能助理r2，你可以问我任何问题！");
        // 标签
        BaseTag tag = new BaseTag();
        tag.setId("1");
        tag.setName("测试");
        tag.setType("primary");
        // 智能体
        BaseAgent baseAgent1 = new BaseAgent();
        baseAgent1.setId("1");
        baseAgent1.setType("办公");
        baseAgent1.setIcon("");
        baseAgent1.setDesc("这是智能体1");
        baseAgent1.setTags(List.of(tag));
        baseAgent1.setConfig(config1);

        BaseAgent baseAgent2 = new BaseAgent();
        baseAgent2.setId("2");
        baseAgent2.setType("办公");
        baseAgent2.setIcon("");
        baseAgent2.setDesc("这是智能体2");
        baseAgent2.setTags(List.of(tag));
        baseAgent2.setConfig(config2);

        List<BaseAgent> all = List.of(baseAgent1, baseAgent2);
        Stream<BaseAgent> stream = all.stream();
        if (query.getKeyword() != null) {
            stream = stream.filter(agent -> agent.getConfig().getName().contains(query.getKeyword()));
        }
        return stream.toList();
    }

    @Override
    public List<BaseHistory> getHistoryList(BaseQuery query) {
        return historyList;
    }

    @Override
    public BaseHistory createHistory(BaseHistory history) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        history.setId(uuid);
        history.setTitle("新对话" + uuid.substring(0, 8));
        historyList.add(history);
        return history;
    }

    @Override
    public Boolean updateHistory(BaseHistory history) {
        String id = history.getId();
        for (int i = 0; i < historyList.size(); i++) {
            BaseHistory baseHistory = historyList.get(i);
            if (baseHistory.getId().equals(id)) {
                historyList.set(i, history);
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean deleteHistory(String id) {
        for (int i = 0; i < historyList.size(); i++) {
            BaseHistory baseHistory = historyList.get(i);
            if (baseHistory.getId().equals(id)) {
                historyList.remove(i);
                return true;
            }
        }
        return false;
    }

    @Override
    public BaseFile uploadFile(MultipartFile file) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        fileMap.put(uuid, file);
        BaseFile baseFile = new BaseFile();
        baseFile.setId(uuid);
        baseFile.setName(file.getOriginalFilename());
        baseFile.setType(file.getContentType());
        baseFile.setSize(file.getSize());
        return baseFile;
    }
}